/*
 * wmain.cpp
 *
 *  Created on: May 30, 2011
 *      Author: Ernest Mashele <mashern@gmail.com>
 */

#define WIN32_LEAN_AND_MEAN  

#include <Windows.h>
#include <tchar.h>
#include <stdlib.h>

#include "graphics.h"

// windows variables
HWND hWnd = NULL;
WCHAR *szTitle = L"Graphics - 04357574";
WCHAR *szWindowClass = L"04357574";

// directx
Graphics *graphics = NULL;

// Forward declarations 
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/,
		LPTSTR /*lpCmdLine*/, int nCmdShow) {

	MSG msg;

	// register the class
	MyRegisterClass(hInstance);

	// initialise application
	if (!InitInstance(hInstance, nCmdShow)) {
		return EXIT_FAILURE;
	}

	// directx
	graphics = new Graphics;
	if (graphics == NULL)
		return EXIT_FAILURE;

	if (!graphics->InitialiseGraphics())
		return EXIT_FAILURE;

	// main message loop:
	while (TRUE) {
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
			// look for quit message
			if (msg.message == WM_QUIT)
				break;

			// decode and pass messages on to WndProc
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}

		// process game loop regardless of windows messages!
		graphics->Render();
	}

	graphics->Cleanup();

	// end program
	return (int) msg.wParam;
}

// set up the window properties
ATOM MyRegisterClass(HINSTANCE hInstance) {
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style = CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc = WndProc;
	wcex.cbClsExtra = 0;
	wcex.cbWndExtra = 0;
	wcex.hInstance = hInstance;
	wcex.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
	wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
	wcex.lpszMenuName = 0;
	wcex.lpszClassName = szWindowClass;
	wcex.hIconSm = wcex.hIcon;

	return RegisterClassEx(&wcex);
}

// create the window and refresh it
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) {

	hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
			CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

	if (!hWnd) {
		return FALSE;
	}

	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);

	return TRUE;
}

// the window event callback function
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {

	switch (message) {
	case WM_CLOSE:
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	case WM_LBUTTONDOWN:
		break;
	case WM_LBUTTONUP:
		break;
	case WM_MOUSEMOVE:
		break;

	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

